<template>
  <div class="monitor-list" v-loading="loading">
    <div class="video-list">
      <div
        v-for="item in videoList"
        :key="item.deviceSerial"
        :class="['video-picture', {'active': deviceId === item.deviceSerial}]"
        @click="playVideo(item.deviceSerial)"
      >
        <img class="picture" :src="item.picUrl" />
        <div class="monitor-title">{{ item.channelName }}</div>
      </div>
    </div>
    <div class="video-box">
      <div class="title">{{videoName}}</div>
      <div id="main" ref="main"></div>
      <!-- <video autoplay controls id="main" ref="main" :src="liveAddress"></video> -->
    </div>
  </div>
</template>

<script>
import { request } from '@/utils/request'
import EZUIKit from 'ezuikit-js'
let player = null
export default {
  name: 'MonitorList',
  data () {
    return {
      loading: true,
      deviceId: null,
      videoList: [],
      liveAddress: ''
    }
  },

  computed: {
    videoName () {
      const device = this.videoList.find(item => item.deviceSerial === this.deviceId)
      return device ? device.channelName : ''
    }
  },

  async mounted () {
    await this.getAccessToken()
    await this.getDeviceList()
    this.init()
    // this.readScreen()
  },

  beforeDestroy () {
    player = null
  },

  methods: {
    async init () {
      if (!this.liveAddress) return
      const { width, height } = this.$refs.main.getBoundingClientRect()
      player = new EZUIKit.EZUIKitPlayer({
        autoplay: true,
        id: 'main',
        accessToken: sessionStorage.getItem('accessToken'),
        url: this.liveAddress,
        // template: 'simple', // simple - 极简版;standard-标准版;security - 安防版(预览回放);voice-语音版；
        // 视频上方头部控件
        // header: ["capturePicture", "save", "zoom"], // 如果templete参数不为simple,该字段将被覆盖
        // plugin: ['talk'],                       // 加载插件，talk-对讲
        // 视频下方底部控件
        footer: ['fullScreen'], // 如果template参数不为simple,该字段将被覆盖
        audio: 0, // 是否默认开启声音 0 - 关闭 1 - 开启
        // openSoundCallBack: data => console.log("开启声音回调", data),
        // closeSoundCallBack: data => console.log("关闭声音回调", data),
        // startSaveCallBack: data => console.log("开始录像回调", data),
        // stopSaveCallBack: data => console.log("录像回调", data),
        // capturePictureCallBack: data => console.log("截图成功回调", data),
        // fullScreenCallBack: data => console.log("全屏回调", data),
        // getOSDTimeCallBack: data => console.log("获取OSDTime回调", data),
        // width: 600,
        // height: 400
        width,
        height
      })
    },
    // 获取access token
    async getAccessToken () {
      const data = {
        appKey: 'ee1a45a1345f4df5b8c8c0e249044d3a',
        appSecret: '0dfd5feebb4ca67eb77054796713c469'
      }

      const url = `https://open.ys7.com/api/lapp/token/get?appKey=${data.appKey}&appSecret=${data.appSecret}`

      const res = await request(url, 'POST')
      if (res.code === '200') {
        sessionStorage.setItem('accessToken', res.data.accessToken)
      }
    },

    // 设备列表信息
    async getDeviceList () {
      const accessToken = sessionStorage.getItem('accessToken')
      // const exp = sessionStorage.getItem('exp')
      // if (accessToken || Date.now() > exp) {
      //   await this.getAccessToken()
      //   accessToken = sessionStorage.getItem('accessToken')
      // }
      const url = `https://open.ys7.com/api/lapp/camera/list?accessToken=${accessToken}`
      const res = await request(url, 'post')
      this.loading = false
      if (res.code === '200') {
        this.videoList = res.data
        this.deviceId = res.data[0].deviceSerial
        await this.getLiveAddress(this.deviceId)
        // this.liveAddress = `ezopen://open.ys7.com/${this.deviceId}/1.live`
      }
    },

    // 获取播放地址
    async getLiveAddress (deviceSerial) {
      const accessToken = sessionStorage.getItem('accessToken')

      const res = await request('/project/live-address', 'post', {
        accessToken,
        deviceSerial
      }).catch((err) => console.log(err))
      if (res.status === 200) {
        const data = JSON.parse(res.text)
        if (data.msg === 'Operation succeeded') {
          this.liveAddress = data.data.url
        } else {
          this.$message({
            type: 'info',
            message: '设备不在线或异常',
            showClose: true
          })
        }
      }
    },

    async playVideo (deviceSerial) {
      if (deviceSerial === this.deviceId) return
      this.deviceId = deviceSerial
      await this.getLiveAddress(deviceSerial)
      console.log(this.liveAddress, '-----')
      if (this.liveAddress) {
        console.log(player, '------')
        if (player) {
          player.stop()
          player.play({
            url: this.liveAddress
          })
        } else {
          this.init()
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.monitor-list {
  display: flex;
  box-sizing: border-box;
  padding: 2rem;
  height: 100%;
}
.video-list {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

  box-sizing: border-box;
  margin-right: 2rem;
  // margin-top: 1.875rem;
  width: 18.75rem;
  height: 100%;
  overflow-y: auto;
  .video-picture {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    margin-bottom: 1.25rem;
    box-sizing: border-box;
    // width: 25rem;
    height: 11.25rem;
    border-radius: .25rem;
    background-color: #000;

    .monitor-title{
      display: inline-block;
      box-sizing: border-box;
      padding: 0 1.5rem;
      height: 1.875rem;
      line-height: 1.875rem;
      font-size: 1rem;

      text-align: left;

      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      background-color: rgba($color: #fff, $alpha: 0.3);
    }

    .picture{
      flex: 1;
      height: 100%;
      object-fit: cover;
    }
  }

  .active{
    border: 3px solid #0049c2;
  }
}
.video-box {
  flex: 1;
  position: relative;
  background-color: #000;
  video {
    width: 100%;
    height: 100%;
  }
  .title {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    line-height: 2.5rem;
    width: 100%;
    padding: 0 1.25rem;
    text-align: left;
    // background-color: rgba($color: #fff, $alpha: 0.2);
  }

  #main{
    height: 100%;
  }
}

.title {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  box-sizing: border-box;
  line-height: 2.5rem;
  width: 18.75rem;
  padding: 0 1.25rem;
  text-align: left;
  // background-color: rgba($color: #fff, $alpha: 0.2);
}
</style>
